// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { computed } from 'vue'

// 路由懒加载
const HomeView = () => import('@/views/HomeView.vue')
const CategoriesView = () => import('@/views/CategoriesView.vue')
const HotView = () => import('@/views/HotView.vue')
const AboutView = () => import('@/views/AboutView.vue')
const NotFoundView = () => import('@/views/NotFoundView.vue')
const NewProfileView = () => import('@/views/NewProfileView.vue') // 新增
const addContentView = () => import('@/views/addContent.vue')

const routes = [
  {
    path: '/',
    name: 'Home',
    component: HomeView,
    meta: {
      title: '首页',
      requiresAuth: false,
      keepAlive: true // 启用页面缓存
    }
  },
  {
    path: '/categories',
    name: 'Categories',
    component: CategoriesView,
    meta: {
      title: '分类浏览',
      requiresAuth: false
    }
  },
  {
    path: '/hot',
    name: 'Hot',
    component: HotView,
    meta: {
      title: '热门内容',
      requiresAuth: false,
      keepAlive: true
    }
  },
  {
    path: '/hot/:tagId?',
    name: 'Hot',
    component: HotView
  },
  {
    path: '/about',
    name: 'About',
    component: AboutView,
    meta: {
      title: '关于我们',
      requiresAuth: false
    }
  },
  {
    path: '/newProfile',
    name: 'NewProfile',
    component: NewProfileView,
    meta: {
      title: '个人中心',
      // requiresAuth: true // 需要登录
    }
  },
  {
    path: '/addContent/:id?',
    name: 'addContent',
    component: addContentView,
  },
  {
    path: '/category/:categoryId',
    name: 'CategoryDetail',
    component: () => import('@/views/CategoryDetailView.vue'),
    meta: {
      title: '分类详情',
      requiresAuth: false
    }
  }
  ,
  {
    path: '/content/:contentId',
    name: 'ContentDetail',
    component: () => import('@/views/ContentDetailView.vue'),
    meta: {
      title: '内容详情',
      requiresAuth: false
    }
  },
  // 404处理必须放在最后
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFoundView,
    meta: {
      title: '页面不存在'
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 返回顶部或保持滚动位置
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})



router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    if (!authStore.isLoggedIn) {
      next({
        name: 'Login',
        query: { redirect: to.fullPath }
      })
      return
    }
  }

  // 检查是否仅限游客访问
  if (to.meta.guestOnly && authStore.isLoggedIn) {
    next({ name: 'Home' })
    return
  }

  next()
})

// 全局后置钩子
router.afterEach((to, from) => {
  // 可以在这里添加页面访问统计等逻辑
})

export default router
